$(function () {
    var remember = Tools.getItem('remember');
    if (remember) {
        if (Tools.json.isJSON(remember)) {
            var remember = Tools.json.parse(remember);
            if (remember.checked) {
                $('#remember').attr('checked', true);
                $('#username').val(remember.username);
            }
            else {
                $('#remember').removeAttr('checked');
            }
        }
    }

    $('#remember').click(function () {
        rememberUserName();
    });


    $('#buttons').bind('click', function () {

        if ($('#username').val() == '') {
            Tools.alert('请输入用户名', function () {
                $('#username').focus();
            });
            return;
        }
        if ($('#password').val() == '') {
            Tools.alert('请输入密码', function () {
                $('#password').focus();
            });
            return;
        }

        var username = $('#username').val();
        var password = $('#password').val();

        loginAjax.login(username, password);

    });


    try {
        var loginInfo = Tools.getItem("loginInfo");
        if (loginInfo && loginInfo != "undefined") {
            Tools.removeItem("loginInfo");
        }
        var uuid = Tools.getItem("uuid");
        if (uuid) {
            Tools.removeItem("uuid");
        }
    }
    catch (err) {
        //alert(err);
    }
    finally {
        //parent.location.href = "login.html?r=" + Math.random();
    }

});
/**
 * 功能对应的方法
 * */
var loginAjax = {
    login: function (username, password) {
        $('.login-process').show();
        $('#message').html('正在登陆，请稍等。');

        // Mock.mock(window.api.logins, {
        //         "code": 200,
        //         "data": {randomKey:'',token:'' }
        // });

        Network.connect(window.api.login, 'POST', {
            username: username,
            password: password
        }, function (res) {
            loginAjax.rememberUserName();
            if (res.code !== ResponseCode.OK) {
                Tools.alert(res.message);
                return;
            }
            $('#message').html('正在进入系统，请等待。');
            setTimeout(function () {
              window.location.href = window.router.index;
            }, 1000);

        });
    },
    rememberUserName: function () {
        var isChecked = $('#remember').is(":checked");
        if (isChecked) {
            var username = $('#username').val();
            var json = {checked: isChecked, username: username};
            Tools.setItem('remember', Tools.json.stringify(json));
        }
        else {
            Tools.removeItem('remember');
        }
    }
};